package com.inputabc.ct.v1.util;

import net.sf.json.JSONArray;
import net.sf.json.JSONObject;

import java.io.BufferedReader;
import java.io.InputStreamReader;
import java.io.OutputStream;
import java.net.HttpURLConnection;
import java.net.URL;
import java.nio.charset.StandardCharsets;
import java.util.Base64;

/**
 * 百度千帆智能翻译工具类
 * @author AI
 */
public class QianfanUtils {
    // 千帆API密钥
    public static String API_KEY = "";
    public static String SECRET_KEY = "";
    
    // 语言代码常量
    public static final String AUTO = "auto";
    public static final String CHINESE = "zh";
    public static final String ENGLISH = "en";
    public static final String JPANESE = "ja";
    public static final String KOREAN = "ko";
    public static final String FRENCH = "fr";
    public static final String GERMAN = "de";
    public static final String SPANISH = "es";
    public static final String RUSSIAN = "ru";
    
    // 千帆API端点 - 获取访问令牌
    private static final String TOKEN_URL = "https://aip.baidubce.com/oauth/2.0/token";
    // 千帆API端点 - 机器翻译
    private static final String TRANSLATE_URL = "https://aip.baidubce.com/rpc/2.0/mt/texttrans/v1";
    
    // 设置连接和读取超时时间
    private static final int CONNECTION_TIMEOUT = 10000; // 10秒
    private static final int READ_TIMEOUT = 15000; // 15秒
    
    // 访问令牌缓存
    private static String accessToken = null;
    private static long tokenExpireTime = 0;
    
    /**
     * 获取访问令牌
     * @return 访问令牌
     * @throws Exception 如有错误抛出异常
     */
    private static String getAccessToken() throws Exception {
        // 检查缓存的令牌是否有效
        long currentTime = System.currentTimeMillis();
        if (accessToken != null && currentTime < tokenExpireTime) {
            return accessToken;
        }
        
        // 构建请求URL
        String urlStr = TOKEN_URL + "?grant_type=client_credentials" +
                "&client_id=" + API_KEY + "&client_secret=" + SECRET_KEY;
        URL url = new URL(urlStr);
        HttpURLConnection connection = (HttpURLConnection) url.openConnection();
        connection.setRequestMethod("POST");
        connection.setDoOutput(true);
        
        // 设置超时
        connection.setConnectTimeout(CONNECTION_TIMEOUT);
        connection.setReadTimeout(READ_TIMEOUT);
        
        // 读取响应
        StringBuilder response = new StringBuilder();
        try (BufferedReader br = new BufferedReader(
                new InputStreamReader(connection.getInputStream(), StandardCharsets.UTF_8))) {
            String responseLine;
            while ((responseLine = br.readLine()) != null) {
                response.append(responseLine.trim());
            }
        } catch (java.net.SocketTimeoutException e) {
            throw new Exception("连接百度千帆API超时，请检查网络或稍后重试");
        } catch (java.net.ConnectException e) {
            throw new Exception("无法连接到百度千帆API服务器，请检查网络连接");
        } catch (java.io.IOException e) {
            // 尝试读取错误流
            try (BufferedReader br = new BufferedReader(
                    new InputStreamReader(connection.getErrorStream(), StandardCharsets.UTF_8))) {
                String responseLine;
                while ((responseLine = br.readLine()) != null) {
                    response.append(responseLine.trim());
                }
            } catch (Exception ex) {
                // 如果读取错误流也失败，直接抛出原始错误
            }
            throw new Exception("与百度千帆API通信失败: " + e.getMessage());
        }
        
        // 解析JSON响应
        JSONObject jsonResponse = JSONObject.fromObject(response.toString());
        accessToken = jsonResponse.getString("access_token");
        // 设置令牌过期时间（令牌有效期通常为30天，这里设置为29天后过期）
        tokenExpireTime = currentTime + 29 * 24 * 60 * 60 * 1000;
        
        return accessToken;
    }
    
    /**
     * 使用千帆API进行翻译
     * @param text 要翻译的文本
     * @param sourceLanguage 源语言
     * @param targetLanguage 目标语言
     * @return 翻译结果
     * @throws Exception 如有错误抛出异常
     */
    public static String translate(String text, String sourceLanguage, String targetLanguage) throws Exception {
        // 处理特殊语言代码情况
        String actualSourceLang = sourceLanguage;
        if ("zh".equals(sourceLanguage) || "zh-CN".equals(sourceLanguage)) {
            actualSourceLang = CHINESE;
        }
        
        String actualTargetLang = targetLanguage;
        if ("zh".equals(targetLanguage) || "zh-CN".equals(targetLanguage)) {
            actualTargetLang = CHINESE;
        }
        
        // 获取访问令牌
        String token = getAccessToken();
        
        // 构建请求URL
        String urlStr = TRANSLATE_URL + "?access_token=" + token;
        URL url = new URL(urlStr);
        HttpURLConnection connection = (HttpURLConnection) url.openConnection();
        connection.setRequestMethod("POST");
        connection.setRequestProperty("Content-Type", "application/json");
        connection.setDoOutput(true);
        
        // 设置超时
        connection.setConnectTimeout(CONNECTION_TIMEOUT);
        connection.setReadTimeout(READ_TIMEOUT);
        
        // 构建请求体JSON
        JSONObject requestJson = new JSONObject();
        requestJson.put("from", actualSourceLang);
        requestJson.put("to", actualTargetLang);
        requestJson.put("q", text);
        
        // 发送请求
        try (OutputStream os = connection.getOutputStream()) {
            byte[] input = requestJson.toString().getBytes(StandardCharsets.UTF_8);
            os.write(input, 0, input.length);
        }
        
        // 读取响应
        StringBuilder response = new StringBuilder();
        try (BufferedReader br = new BufferedReader(
                new InputStreamReader(connection.getInputStream(), StandardCharsets.UTF_8))) {
            String responseLine;
            while ((responseLine = br.readLine()) != null) {
                response.append(responseLine.trim());
            }
        } catch (java.net.SocketTimeoutException e) {
            throw new Exception("连接百度千帆翻译API超时，请检查网络或稍后重试");
        } catch (java.net.ConnectException e) {
            throw new Exception("无法连接到百度千帆翻译API服务器，请检查网络连接");
        } catch (java.io.IOException e) {
            // 尝试读取错误流
            try (BufferedReader br = new BufferedReader(
                    new InputStreamReader(connection.getErrorStream(), StandardCharsets.UTF_8))) {
                String responseLine;
                while ((responseLine = br.readLine()) != null) {
                    response.append(responseLine.trim());
                }
            } catch (Exception ex) {
                // 如果读取错误流也失败，直接抛出原始错误
            }
            throw new Exception("与百度千帆翻译API通信失败: " + e.getMessage());
        }
        
        // 解析JSON响应
        JSONObject jsonResponse = JSONObject.fromObject(response.toString());
        // 如果响应中包含result字段，则返回翻译结果
        if (jsonResponse.has("result") && jsonResponse.get("result") instanceof JSONObject) {
            JSONObject result = jsonResponse.getJSONObject("result");
            if (result.has("trans_result")) {
                JSONArray transResults = result.getJSONArray("trans_result");
                if (transResults.size() > 0) {
                    JSONObject firstResult = transResults.getJSONObject(0);
                    if (firstResult.has("dst")) {
                        return firstResult.getString("dst");
                    }
                }
            }
        }
        
        // 如果无法解析翻译结果，则抛出异常
        throw new Exception("无法解析翻译结果: " + response.toString());
    }
    
    /**
     * 智能翻译
     * 如果API密钥未设置或翻译请求失败，会尝试使用基本翻译逻辑
     */
    public static String smartTranslate(String text, String sourceLanguage, String targetLanguage) {
        try {
            // 如果文本为空，直接返回
            if (text == null || text.trim().isEmpty()) {
                return "";
            }
            
            // 验证API密钥是否设置
            if (API_KEY == null || API_KEY.isEmpty() || SECRET_KEY == null || SECRET_KEY.isEmpty()) {
                // 返回未设置密钥的提示信息
                return "（百度千帆API密钥未设置，请在设置中配置API Key和Secret Key）" + text;
            }
            
            // 尝试使用API翻译
            try {
                return translate(text, sourceLanguage, targetLanguage);
            } catch (Exception e) {
                // 当API不可用时，使用内置翻译逻辑
                System.out.println("千帆API调用失败，使用内置翻译逻辑: " + e.getMessage());
                
                // 简单翻译逻辑 - 仅作为备用
                if (sourceLanguage.equals(ENGLISH) && targetLanguage.equals(CHINESE)) {
                    // 英译中的常见短语
                    if (text.equalsIgnoreCase("hello")) return "你好";
                    if (text.equalsIgnoreCase("thank you")) return "谢谢";
                    if (text.equalsIgnoreCase("sorry")) return "对不起";
                    if (text.equalsIgnoreCase("goodbye")) return "再见";
                    if (text.equalsIgnoreCase("yes")) return "是";
                    if (text.equalsIgnoreCase("no")) return "否";
                    if (text.equalsIgnoreCase("please")) return "请";
                    if (text.equalsIgnoreCase("welcome")) return "欢迎";
                } else if (sourceLanguage.equals(CHINESE) && targetLanguage.equals(ENGLISH)) {
                    // 中译英的常见短语
                    if (text.equals("你好")) return "hello";
                    if (text.equals("谢谢")) return "thank you";
                    if (text.equals("对不起")) return "sorry";
                    if (text.equals("再见")) return "goodbye";
                    if (text.equals("是")) return "yes";
                    if (text.equals("否")) return "no";
                    if (text.equals("请")) return "please";
                    if (text.equals("欢迎")) return "welcome";
                } else if (sourceLanguage.equals(JPANESE) && targetLanguage.equals(CHINESE)) {
                    // 日译中的常见短语
                    if (text.equals("こんにちは")) return "你好";
                    if (text.equals("ありがとう")) return "谢谢";
                    if (text.equals("さようなら")) return "再见";
                } else if (sourceLanguage.equals(CHINESE) && targetLanguage.equals(JPANESE)) {
                    // 中译日的常见短语
                    if (text.equals("你好")) return "こんにちは";
                    if (text.equals("谢谢")) return "ありがとう";
                    if (text.equals("再见")) return "さようなら";
                }
            }
            
            // 如果未能翻译，返回原文
            return "（翻译服务暂不可用）" + text;
            
        } catch (Exception ex) {
            // 出现异常时返回原文
            System.err.println("翻译出错: " + ex.getMessage());
            return text;
        }
    }
} 